package com.lujieni.netty.selfaggrement;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

@Slf4j
public class LujieniCodec extends MessageToMessageCodec<ByteBuf, Message> {

    /**
     * @param ctx
     * @param msg
     * @param out
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        //ByteBuf bb = ctx.alloc().buffer();
        ByteBuf bb = ByteBufAllocator.DEFAULT.buffer();
        bb.writeBytes(new byte[]{1, 2, 3, 4}); // symbol of aggrement 4bytes
        //使用jdk序列化方式将msg 序列化成字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
        oos.writeObject(msg);
        byte[] mseeagePayload = byteArrayOutputStream.toByteArray();
        bb.writeInt(mseeagePayload.length); // length of message
        bb.writeBytes(mseeagePayload); // message itself
        out.add(bb);
    }

    /**
     * @param ctx
     * @param in
     * @param out
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int symbol = in.readInt();
        int length = in.readInt();
        byte[] messagePayload = new byte[length];
        in.readBytes(messagePayload,0, length);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(messagePayload));
        Message message = (Message)ois.readObject();
        //log.info("symbol:{}", symbol);
        //log.info("length:{}", length);
        //log.info("message:{}", message);
        out.add(message);
    }

}
